<template>
  <div class="top-right-btn" :style="style">
    <el-row>
      <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top" v-if="search">
        <el-button circle icon="Search" @click="toggleSearch()" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button circle icon="Refresh" @click="refresh()" />
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="显隐列" placement="top" v-if="columns">
        <el-button circle icon="Menu" @click="showColumn()" v-if="showColumnsType == 'transfer'"/>
        <el-dropdown trigger="click" :hide-on-click="false" style="padding-left: 12px" v-if="showColumnsType == 'checkbox'">
          <el-button circle icon="Menu" />
          <template #dropdown>
            <el-dropdown-menu>
              <template v-for="item in localColumns" :key="item.key">
                <el-dropdown-item>
                  <el-checkbox
                      v-model="item.visible"
                      @change="checkboxChange($event, item.key)"
                  >
                    {{ item.label }}
                  </el-checkbox>
                </el-dropdown-item>
              </template>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-tooltip>
    </el-row>
    <el-dialog :title="title" v-model="open" append-to-body>
      <el-transfer
          :titles="['显示', '隐藏']"
          v-model="transferValue"
          :data="transferData"
          @change="dataChange"
      ></el-transfer>
    </el-dialog>
  </div>
</template>

<script setup>
const props = defineProps({
  /* 是否显示检索条件 */
  showSearch: {
    type: Boolean,
    default: true,
  },
  /* 显隐列信息 */
  columns: {
    type: Array,
    required: true,
  },
  /* 是否显示检索图标 */
  search: {
    type: Boolean,
    default: true,
  },
  /* 显隐列类型（transfer穿梭框、checkbox复选框） */
  showColumnsType: {
    type: String,
    default: "checkbox",
  },
  /* 右外边距 */
  gutter: {
    type: Number,
    default: 10,
  },
})

const emits = defineEmits(['update:showSearch', 'queryTable', 'update:columns']);

// 显隐数据
const transferValue = ref([]);
// 弹出层标题
const title = ref("显示/隐藏");
// 是否显示弹出层
const open = ref(false);

// 创建内部副本，解决状态不同步问题
const localColumns = ref([...props.columns]);

const style = computed(() => {
  const ret = {};
  if (props.gutter) {
    ret.marginRight = `${props.gutter / 2}px`;
  }
  return ret;
});

// 处理 transfer 组件的数据格式
const transferData = computed(() => {
  return localColumns.value.map(item => ({
    key: item.key,
    label: item.label,
    disabled: false
  }));
});

// 搜索
function toggleSearch() {
  emits("update:showSearch", !props.showSearch);
}

// 刷新
function refresh() {
  emits("queryTable");
}

// 右侧列表元素变化
function dataChange(value) {
  // 创建新的 columns 数组
  const newColumns = localColumns.value.map(item => ({
    ...item,
    visible: !value.includes(item.key)
  }));

  // 更新内部状态
  localColumns.value = newColumns;

  // 通知父组件更新 columns
  emits('update:columns', newColumns);
}

// 打开显隐列dialog
function showColumn() {
  // 每次打开时重新同步数据
  updateTransferValue();
  open.value = true;
}

// 更新 transferValue
function updateTransferValue() {
  transferValue.value = localColumns.value
      .filter(item => !item.visible)
      .map(item => item.key);
}

// 勾选
function checkboxChange(event, key) {
  // 创建新的 columns 数组
  const newColumns = localColumns.value.map(item => {
    if (item.key === key) {
      return { ...item, visible: event };
    }
    return item;
  });

  // 更新内部状态
  localColumns.value = newColumns;

  // 通知父组件更新 columns
  emits('update:columns', newColumns);
}

// 监听 columns 变化，更新内部副本
watch(() => props.columns, (newColumns) => {
  // 使用深拷贝确保内部状态与 prop 同步
  localColumns.value = JSON.parse(JSON.stringify(newColumns));

  if (props.showColumnsType === 'transfer') {
    updateTransferValue();
  }
}, { deep: true, immediate: true });

// 监听 showColumnsType 变化，重置相应状态
watch(() => props.showColumnsType, (newType) => {
  if (newType === 'transfer') {
    updateTransferValue();
  }
});

// 组件挂载时初始化
onMounted(() => {
  if (props.showColumnsType === 'transfer') {
    updateTransferValue();
  }
});
</script>

<style lang='scss' scoped>
:deep(.el-transfer__button) {
  border-radius: 50%;
  display: block;
  margin-left: 0px;
}
:deep(.el-transfer__button:first-child) {
  margin-bottom: 10px;
}
:deep(.el-dropdown-menu__item) {
  line-height: 30px;
  padding: 0 17px;
}

/* 修复复选框样式 */
:deep(.el-dropdown-menu__item .el-checkbox) {
  width: 100%;
  display: flex;
  align-items: center;
  margin-right: 0;
}

/* 确保标签文本可以点击 */
:deep(.el-dropdown-menu__item .el-checkbox__label) {
  padding-left: 5px;
  cursor: pointer;
}
</style>